<!doctype html>
<html lang="zh_cn" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>房东辅助系统</title>
    <link rel="stylesheet" type="text/css" href="../static/css/bootstrap.css">
    <script type="text/javascript" src="../static/js/jquery.min.js"></script>
    <script type="text/javascript" src="../static/js/bootstrap.bundle.js"></script>
</head>
<body>
    <div class="container bg-dark-subtle vh-100">
        <div class="row py-5">
            <div class="col ms-3 small">欢迎您：<span id="userInfo" class="fw-bold" th:text="${userName+','+mobile}">杨磊磊,15210831334</span></div>
        </div>
        <div class="row py-2 mt-1 bg-light-subtle">
            <div class="col-8 fw-bold">水费价格（元/吨）：</div>
            <div class="col-4 text-end"><span id="watPrice" class="fw-bold"></span> <img src="../static/img/pencil.png" class="img-fluid btn p-1" onclick="editWatPrice()"></div>
        </div>
        <div class="row py-2">
            <div class="col-8 fw-bold">电费价格（元/度）：</div>
            <div class="col-4 text-end"><span id="elePrice" class="fw-bold"></span> <img src="../static/img/pencil.png" class="img-fluid btn p-1" onclick="editElePrice()"></div>
        </div>
        <div class="row py-2 bg-light-subtle">
            <div class="col-8 fw-bold">每月收租日：</div>
            <div class="col-4 text-end"><span id="rentDay" class="fw-bold"> </span> <img src="../static/img/pencil.png" class="img-fluid btn p-1" onclick="editRentDay()"></div>
        </div>
        <div class="row py-2">
            <div class="col-8 fw-bold">楼栋数量：</div>
            <div class="col-4 text-end"><span id="buildings" class="fw-bold"> </span> <img src="../static/img/edit_add.png" class="img-fluid btn p-1" onclick="addBuilding()"></div>
        </div>
        <div class="row py-2 bg-light-subtle">
            <div class="col-8 fw-bold">房间数量：</div>
            <div class="col-4 text-end"><span id="rooms" class="fw-bold"> </span> <img src="../static/img/edit_add.png" class="img-fluid btn p-1" onclick="addRoom()"></div>
        </div>
        <div class="row py-2">
            <div class="col-8 fw-bold">待出租房间数量：</div>
            <div class="col-4 text-end fw-bold" id="emptyRooms"></div>
        </div>
        <div class="row py-2 bg-light-subtle">
            <div class="col-8 fw-bold">租金水电总收入(元)：</div>
            <div id="recTotal" class="col-4 text-end fw-bold"></div>
        </div>
        <div class="row py-2">
            <div class="col-8 fw-bold">租金总收入(元)：</div>
            <div id="rentTotal" class="col-4 text-end fw-bold"></div>
        </div>
        <div class="row py-2 bg-light-subtle">
            <div class="col-8 fw-bold">水费收入(元)：</div>
            <div id="watTotal" class="col-4 text-end fw-bold"></div>
        </div>
        <div class="row py-2">
            <div class="col-8 fw-bold">电费收入(元)：</div>
            <div id="eleTotal" class="col-4 text-end fw-bold"></div>
        </div>
        <div class="row py-2 bg-light-subtle align-items-center">
            <div class="col-auto" style="width: 48%;">
                <input id="startDate" type="date" class="form-control p-1" th:value="${start}">
            </div>
            <div class="col-auto text-center p-0" style="width: 4%;">
                <span class="form-control-plaintext p-1">-</span>
            </div>
            <div class="col-auto" style="width: 48%;">
                <input id="endDate" type="date" class="form-control p-1" th:value="${end}">
            </div>
        </div>
        <div class="row py-2">
            <div class="col-7 text-end p-1">
                <span class="form-control-plaintext" style="font-size: small">统计起止日期</span>
            </div>
            <div class="col-5 p-1">
                <a class="btn btn-secondary rounded-3 p-1" style="font-size: small" id="reloadBtn" onclick="reload()">
                    重新加载<span id="loadingSpinner" class="spinner-border spinner-border-sm ms-1" style="display: none;" role="status" aria-hidden="true"></span>
                </a>
            </div>
        </div>
        <div class="btn-group fixed-bottom justify-content-center">
            <a href="#" class="btn btn-primary active rounded-0">首页</a>
            <a href="/page/settings.html" class="btn btn-primary rounded-0">管理</a>
        </div>
    </div>

    <!-- 错误提示框 -->
    <div class="modal fade" id="errModal" tabindex="-1" aria-labelledby="modalLabErr" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabErr">错误提示</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-info text-center" id="err-body"></div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
                    <!--                    <button type="button" class="btn btn-primary">Save changes</button>-->
                </div>
            </div>
        </div>
    </div>

    <!-- 修改水价提示框 -->
    <div class="modal fade" id="editWatPriceModal" tabindex="-1" aria-labelledby="modalLabWater" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabWater">修改水价</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <label for="watPriceInput" class="form-label">水费价格</label>
                    <input type="number" class="form-control" id="watPriceInput" aria-describedby="watPriceBlock" placeholder="请输入水费价格" required />
                    <div id="watPriceBlock" class="form-text text-info small">
                        &nbsp;&nbsp;水费价格单位是元/吨，最多支持2位小数，修改后只对后面收取的水费计算生效。
                    </div>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-primary" id="saveWatPriceBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改电价提示框 -->
    <div class="modal fade" id="editElePriceModal" tabindex="-1" aria-labelledby="modalLabEle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabEle">修改电价</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <label for="elePriceInput" class="form-label">电费价格</label>
                    <input type="number" class="form-control" id="elePriceInput" aria-describedby="elePriceBlock" placeholder="请输入电费价格" required />
                    <div id="elePriceBlock" class="form-text text-info small">
                        &nbsp;&nbsp;电费价格单位是元/度，最多支持2位小数，修改后只对后面收取的电费计算生效。
                    </div>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-primary" id="saveElePriceBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改每月收租日提示框 -->
    <div class="modal fade" id="editRentDayModal" tabindex="-1" aria-labelledby="modalLabRentDay" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabRentDay">修改收租日</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <label for="rentDayInput" class="form-label">每月收租日</label>
                    <input type="number" class="form-control" id="rentDayInput" aria-describedby="rentDayBlock" placeholder="请输入每月收租日" required />
                    <div id="rentDayBlock" class="form-text text-info small">
                        &nbsp;&nbsp;收租日为1到31之间的整数；收租日修改后，房间租金按照上个收租日到新的收租日的天数差计算本月租金。
                    </div>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-primary" id="saveRentDayBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加楼栋 -->
    <div class="modal fade" id="addBuildingModal" tabindex="-1" aria-labelledby="modalLabAddBuilding" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabAddBuilding">添加楼栋</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0">
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="buildingNameInput" class="col-form-label-sm">楼栋简称</label>
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control form-control-sm" id="buildingNameInput" aria-describedby="buildingNameBlock" placeholder="请输入楼栋简称" required />
                        </div>
                    </div>
                    <div class="row mx-1 ">
                        <div id="buildingNameBlock" class="form-text text-info small">
                            &nbsp;&nbsp;楼栋简称不能重复，长度10个字符以内。
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="buildingAddressInput" class="form-label small">楼栋简称</label>
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control form-control-sm" id="buildingAddressInput" aria-describedby="buildingAddressBlock" placeholder="请输入楼栋地址" required />
                        </div>
                    </div>
                    <div class="row mx-1">
                        <div id="buildingAddressBlock" class="form-text text-info small">
                            &nbsp;&nbsp;楼栋地址,长度30个字符以内。
                        </div>
                    </div>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-primary" id="saveBuildingBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加房间 -->
    <div class="modal fade" id="addRoomModal" tabindex="-1" aria-labelledby="modalLabAddRoom" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabAddRoom">添加房间</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0">
                    <div class="row mx-1 my-2">
                        <div class="col-4">
                            <label for="buildingSelect" class="col-form-label-sm">选择楼栋</label>
                        </div>
                        <div class="col-8">
                            <select id="buildingSelect" class="form-control form-select-sm" required></select>
                        </div>
                    </div>
                    <div class="row mx-1 my-2">
                        <div class="col-4">
                            <label for="roomNameInput" class="col-form-label-sm">房间名</label>
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control form-control-sm" id="roomNameInput" placeholder="请输入房间名或房间号" required />
                        </div>
                    </div>
                    <div class="row mx-1 my-2">
                        <div class="col-4">
                            <label for="watNumInput" class="col-form-label-sm">当前水表数</label>
                        </div>
                        <div class="col-8">
                            <input type="number" class="form-control form-control-sm" id="watNumInput" placeholder="请输入水表后5位数" required />
                        </div>
                    </div>
                    <div class="row mx-1 my-2">
                        <div class="col-4">
                            <label for="eleNumInput" class="col-form-label-sm">当前电表数</label>
                        </div>
                        <div class="col-8">
                            <input type="number" class="form-control form-control-sm" id="eleNumInput" aria-describedby="addRoomBlock" placeholder="请输入电表后5位数" required />
                        </div>
                    </div>
                    <div class="row mx-1 my-2">
                        <div id="addRoomBlock" class="form-text small text-danger"></div>
                    </div>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-primary" id="saveRoomBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

</body>
<script type="text/javascript">
    $(function () {
        reload();
    });

    function editWatPrice() {
        $("#editWatPriceModal").modal('show');
    }

    // 修改水费价格
    document.getElementById("saveWatPriceBtn").addEventListener("click", saveWatPrice);
    function saveWatPrice() {
        const watPrice = $("#watPriceInput").val();
        if (watPrice.length === 0 || watPrice < 0) {
            $("#watPriceBlock").text("水价不能为空或小于0");
            return;
        }

        $.ajax({
            url: '/api/user/resetWatPrice',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({price: watPrice}),
            success: function(res) {
                if (res.code === 1) {
                    $("#watPriceBlock").text(res.message);
                    return;
                }
                $("#watPrice").text(watPrice);
                // 隐藏修改价格弹窗
                $("#editWatPriceModal").modal('hide');
            },
            error: function(xhr, status, error) {
                // 检查是否是重定向状态码
                if (xhr.status === 401) {
                    // 手动导航到重定向URL
                    window.location.href = "/page/login.html";
                } else {
                    // 显示错误提示框并输出错误信息
                    $("#watPriceBlock").text("系统异常，请求失败" + xhr.status);
                }
            }
        });
    }

    function editElePrice() {
        $("#editElePriceModal").modal('show');
    }

    // 修改电费价格
    document.getElementById("saveElePriceBtn").addEventListener("click", saveElePrice);
    function saveElePrice() {
        const elePrice = $("#elePriceInput").val();
        if (elePrice.length === 0 || elePrice < 0) {
            $("#elePriceBlock").text("电费价格不能为空或小于0");
            return;
        }

        $.ajax({
            url: '/api/user/resetElePrice',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({price: elePrice}),
            success: function(res) {
                if (res.code === 1) {
                    $("#elePriceBlock").text(res.message);
                    return;
                }
                $("#elePrice").text(elePrice);
                // 隐藏修改价格弹窗
                $("#editElePriceModal").modal('hide');
            },
            error: function(xhr, status, error) {
                // 检查是否是重定向状态码
                if (xhr.status === 401) {
                    // 手动导航到重定向URL
                    window.location.href = "/page/login.html";
                } else {
                    // 显示错误提示框并输出错误信息
                    $("#elePriceBlock").text("系统异常，请求失败" + xhr.status);
                }
            }
        });
    }

    function editRentDay() {
        $("#editRentDayModal").modal('show');
    }
    // 修改每月收租日期
    document.getElementById("saveRentDayBtn").addEventListener("click", saveRentDay);
    function saveRentDay() {
        const rentDay = $("#rentDayInput").val();
        if (rentDay.length === 0 || rentDay < 1 || rentDay > 31) {
            $("#rentDayBlock").text("收租日为1到31之间的整数");
            return;
        }

        $.ajax({
            url: '/api/user/resetRentDay',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({day: rentDay}),
            success: function(res) {
                if (res.code === 1) {
                    $("#rentDayBlock").text(res.message);
                    return;
                }
                $("#rentDay").text(rentDay);
                $("#editRentDayModal").modal('hide');
            },
            error: function(xhr, status, error) {
                // 检查是否是重定向状态码
                if (xhr.status === 401) {
                    // 手动导航到重定向URL
                    window.location.href = "/page/login.html";
                } else {
                    // 显示错误提示框并输出错误信息
                    $("#rentDayBlock").text("系统异常，请求失败" + xhr.status);
                }
            },
        });
    }

    function addBuilding() {
        //清空原有的内容
        $("#buildingNameInput").val('');
        $("#buildingAddressInput").val('');
        $("#addBuildingModal").modal('show');
    }

    // 添加收租楼栋
    document.getElementById("saveBuildingBtn").addEventListener("click", saveBuilding);
    function saveBuilding() {
        const buildingName = $("#buildingNameInput").val();
        const address = $("#buildingAddressInput").val();
        if (buildingName == null || address == null || buildingName.length > 10 || address.length > 30) {
            $("#buildingAddressBlock").text("表单填写不正确");
            return;
        }

        $.ajax({
            url: '/api/building/addBuilding',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({name: buildingName, address: address}),
            success: function(res) {
                if (res.code === 1) {
                    $("#buildingAddressBlock").text(res.message);
                    return;
                }
                // 隐藏弹窗
                $("#addBuildingModal").modal('hide');
                reload();
            },
            error: function(xhr, status, error) {
                // 检查是否是重定向状态码
                if (xhr.status === 401) {
                    // 手动导航到重定向URL
                    window.location.href = "/page/login.html";
                } else {
                    // 显示错误提示框并输出错误信息
                    $("#buildingAddressBlock").text("系统异常，请求失败" + xhr.status);
                }
            }
        });
    }

    function addRoom() {
        //清空原有的内容
        $("#buildingNameInput").val('');
        $("#buildingAddressInput").val('');
        $("#addRoomModal").modal('show');
        // 重新加载楼栋列表
        reloadBuildingList();
    }

    function reloadBuildingList() {
        $.ajax({
            url: '/api/building/list',
            contentType:'application/json;charset=utf-8',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {
                    $("#addRoomBlock").text(res.message);
                    return;
                }
                if (res.data.length === 0) {
                    return;
                }
                $("#buildingSelect").html('');
                res.data.forEach(function(building, index) {
                    if (index === 0) {
                        $("#buildingSelect").append('<option value="' + building.id + '" selected>' + building.name + '</option>');
                    } else {
                        $("#buildingSelect").append('<option value="' + building.id + '">' + building.name + '</option>');
                    }
                });
            },
            error: function(xhr, status, error) {
                // 检查是否是重定向状态码
                if (xhr.status === 401) {
                    // 手动导航到重定向URL
                    window.location.href = "/page/login.html";
                } else {
                    // 显示错误提示框并输出错误信息
                    $("#addRoomBlock").text("系统异常，请求失败" + xhr.status);
                }
            }
        });
    }

    // 添加房间
    document.getElementById("saveRoomBtn").addEventListener("click", saveRoom);
    function saveRoom() {
        const buildingId = $("#buildingSelect").val();
        const roomName = $("#roomNameInput").val();
        const curWaterNum = $("#watNumInput").val();
        const curEleNum = $("#eleNumInput").val();
        if (buildingId == null || roomName == null || curWaterNum == null || curEleNum == null) {
            $("#addRoomBlock").text("表单填写不正确");
            return;
        }

        $.ajax({
            url: '/api/room/addRoom',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({buildingId: buildingId, name: roomName, waterNum: curWaterNum, electricNum: curEleNum}),
            success: function(res) {
                if (res.code === 1) {
                    $("#addRoomBlock").text(res.message);
                    return
                }
                // 隐藏修改价格弹窗
                $("#addRoomModal").modal('hide');
                reload();
            },
            error: function(xhr, status, error) {
                // 检查是否是重定向状态码
                if (xhr.status === 401) {
                    // 手动导航到重定向URL
                    window.location.href = "/page/login.html";
                } else {
                    // 显示错误提示框并输出错误信息
                    $("#addRoomBlock").text("系统异常，请求失败" + xhr.status);
                }
            }
        });
    }

    function reload() {
        const startDay = $("#startDate").val();
        const endDay = $("#endDate").val();
        // 显示加载动画
        $("#loadingSpinner").show();

        $.ajax({
            url: '/api/user/main',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({startDate: startDay, endDate: endDay}),
            success: function(res) {
                if (res.code === 1) {
                    $("#err-body").text(res.message);
                    $("#errModal").modal('show');
                    return;
                }
                $("#watPrice").text(res.data.waterPrice);
                $("#elePrice").text(res.data.electricPrice);
                $("#rentDay").text(res.data.rentDay);
                $("#buildings").text(res.data.buildingTotal);
                $("#rooms").text(res.data.roomTotal);
                $("#emptyRooms").text(res.data.emptyRoomTotal);
                $("#recTotal").text(res.data.recTotal);
                $("#rentTotal").text(res.data.rentTotal);
                $("#watTotal").text(res.data.waterTotal);
                $("#eleTotal").text(res.data.electricTotal);
            },
            error: function(xhr, status, error) {
                // 检查是否是重定向状态码
                if (xhr.status === 401) {
                        // 手动导航到重定向URL
                    window.location.href = "/page/login.html";
                } else {
                    // 显示错误提示框并输出错误信息
                    $("#err-body").text("系统异常，请求失败" + xhr.status);
                    $("#errModal").modal('show');
                }
            },
            complete: function() {
                // 隐藏加载动画
                $("#loadingSpinner").hide();
            }
        });
    }
</script>
</html>